import axios from "axios"

import config from "./config"

import { showFailToast } from "vant"

import { useUserStore } from "@/store/user"

import { cookie } from "@/utils/cookie"

import { errorAction } from "./catch"

const instance = axios.create(config)

// 添加请求拦截器
instance.interceptors.request.use(async (config: any) => {
  try {
    const store = useUserStore()
    switch(true){
      case (([null, undefined, 'undefined'].includes(store.accessToken))): 
          config.headers.Authorization = 'Basic ' + cookie.getItem('basicHeader')
        break
      default: 
        config.headers.Authorization = 'Bearer ' + cookie.getItem('accessToken')
        break
    }
    return config
  } catch(err){ throw err }
}, (error: unknown) => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use((response: any) => {
  const store = useUserStore()
  switch(true){
    // 2xx 范围内的状态码都会触发该函数。 对响应数据做点什么
    case (response?.data?.success && response.status === 200):
      return response.data
    // axios在请求的 status === 200 时会认为请求成功 这里处理 status === 200 但 success 为false 的错误
    // 判断 response.data.success 为 false 时的错误处理  status !== 200 axios会自动到error函数
    case (!response.data.success && response.status === 401): 
      showFailToast(response.data.message)
      return store.logout()
    case (!response.data.success): 
        errorAction(response.data)
      return response.data
    default: return response.data
  }
}, (error: any) => {
  errorAction(error?.response?.data)
  return Promise.reject(error)
})

export default instance
